package com.xxh.blog.shiro;

import cn.hutool.json.JSONUtil;
import com.xxh.blog.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authc.UserFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class auFilter extends UserFilter {


    @Override
    protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {

        //(请求是ajax，返回就是ajax)ajax请求给返回json数据
        HttpServletResponse httpresponse=(HttpServletResponse)response;
        String header = httpresponse.getHeader("X-Requested-With");
        if(header!=null&&header.equals("XMLHttpRequest")){
            boolean authenticated = SecurityUtils.getSubject().isAuthenticated();
            if(!authenticated){
                request.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                response.getWriter().write(JSONUtil.toJsonStr(Result.error("请登陆之后再操作")));
            }
        }else {
            //普通的web 请求可以重定向
            super.redirectToLogin(request, response);
        }

    }
}
